﻿using Aker.DevTeam;
using Aker.MainForms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
using Extensions;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace Aker.Uretim
{
    public partial class Siparisler : XForm
    {
        public Siparisler()
        {
            InitializeComponent();

            orderedColumns = new string[] {
                                                    "Thumb",
                                                    "BazArtikel",
                                                    "Artikel",
                                                    "Design",
                                                    "Weight",
                                                    "Width",
                                                    "Composition",
                                                    //"Qty",
                                                    "KG",
                                                    "Meters",
                                                    "Yards",                                                    
                                                    "Price",
                                                    "Notes",                                                   
                                                    "LineTotal",
                                                    "TotalTransfered",
                                                    "ETA",
                                                    "MusteriKodu",
                                                    //"NewTransferMT",
                                                    //"NewTransferKG",
                                                    //"TopAdedi",
                                                    //"MalCinsi",
                                                     "Status"
                                                    };

            SiparisTipi = 1;
        }

        int SiparisTipi;

        public static DataTable dtSatilanIplik = new DataTable();

        public Siparisler(int SiparisTipi)
        {
            InitializeComponent();
            this.SiparisTipi = SiparisTipi;

            orderedColumns = new string[] {
                                                    "Grup",
                                                    //"İplik",
                                                    "BirimAdet",
                                                    "KG",
                                                    "Price",
                                                    "Notes",                                                   
                                                    "LineTotal",
                                                    "TotalTransfered",
                                                    "ETA", 
                                                    "Status"
                                                    };

        }


        string[] orderedColumns;
        private void BindData()
        {
            ds = Data.DM.ExecuteDataSet("GetPOrders", true, SiparisTipi);
            DataTable dtDetail = ds.Tables[1];
            dtDetail.Columns.Add("İplik", typeof(string));

            if (SiparisTipi == 1)
            {
                foreach (DataRow dr in dtDetail.Rows)
                {
                    int bazProductId = dr["BazProductId"].ToIntNN();
                    if (bazProductId > -1)
                    {
                        DataRow pr = Data.DB.Product.Select("ProductId = " + bazProductId)[0];

                        foreach (string col in Data.ProductDetails)
                        {
                            if (!dtDetail.Columns.Contains(col))
                                dtDetail.Columns.Add(col, typeof(string));
                            if (pr != null)
                                dr[col] = pr[col];
                        }
                    }
                }
            }
            else if (SiparisTipi == 2)
            {
                //foreach (DataRow dr in dtDetail.Rows)
                //{
                //    DataRow ir = dtSatilanIplik.Select("IplikId = " + dr["IplikId"])[0];
                //    dr["İplik"] = ir["Iplik"];
                //}
            }

            ds.Relations.Add("Sipariş Detayı", ds.Tables[0].Columns["POrderId"], ds.Tables[1].Columns["POrderId"]);
            bs = new BindingSource(ds, ds.Tables[0].TableName);
            BindingSource bsDetail = new BindingSource(bs, "Sipariş Detayı");

            ds.Tables[0].Columns.Add("TotalTransfered", typeof(decimal), "SUM(Child.TotalTransfered)");

            dtDetail.AcceptChanges();

            gvPOrder.Init(bs);

            gvLines.Init(bsDetail);


            DevExpress.XtraEditors.Repository.RepositoryItemMemoEdit riMemo = new DevExpress.XtraEditors.Repository.RepositoryItemMemoEdit();
            gvPOrder.Columns["Notes"].ColumnEdit = riMemo;
            gvPOrder.Columns["Notes"].AppearanceCell.TextOptions.VAlignment = DevExpress.Utils.VertAlignment.Center;

            gvLines.MakeColumnInvisible("POrderId", "POrderLinesId", "ProductId");

            GridColumn gc = new GridColumn();
            gc.Name = "Thumb";
            gc.Caption = "";
            gc.FieldName = "Thumb";
            gc.VisibleIndex = 0;
            gvLines.Columns.Add(gc);


            gvLines.SetVisibleIndex(orderedColumns);

            gvLines.SetCaptions("ProductId:Artikel Id", "Thumb:Resim", "Design:Desen", "Composition:Karışm", "Width:En", "Weight:Ağırlık", "Meters:Metre", "Notes:Notlar",
                    "Price:Fiyat", "LineTotal:Satır Toplamı", "TotalTransfered:Toplam Sevkiyat", "NewTransferMT:Yeni Sevk (MT)", "NewTransferKG:Yeni Sevk (KG)", "Status:Durum"
                    );

            if (SiparisTipi == 2)
                gvLines.SetCaptions("MusteriKodu:İplik");

            gvLines.MakeColumnInvisible("POrderId");
            gvLines.AddSummary("LineTotal", "NewTransferKG", "NewTransferMT", "TotalTransfered");
            gvLines.MakeReadOnly("NewTransferKG", "NewTransferMT", "TopAdedi", "MalCinsi");
            gvLines.FormatAsNumber("Meters", "KG", "Price", "LineTotal");

            gvLines.BestFitColumns();

            gvPOrder.SetCaptions("POrderId:Sip.No", "OrderDate:Sipariş Tarihi", "Brand:Müşteri", "SiparisiAlan:Siparişi Alan", "KalanGun:Kalan Gün", "ToplamArtikel:Artikel Adedi", "PaymentType:Ödeme Şekli",
            "Currency:Parabirimi", "Status:Durum", "ETA:Termin", "Notes:Notlar");

            gvPOrder.FormatAsNumber("ToplamKG", "ToplamMT", "Tutar");

            gvPOrder.AddSummary("TotalTransfered");
            gvPOrder.BestFitColumns();

            gvPOrder.Columns["Notes"].Width = 250;
            gvPOrder.Columns["Status"].Width = 100;

            //if (!AppSession.UserInfo.Yonetici)
            //{
            //    gvPOrder.Columns["Tutar"].Visible = gvLines.Columns["Price"].Visible = gvLines.Columns["LineTotal"].Visible = false;
            //    gvPOrder.Columns["Tutar"].OptionsColumn.ShowInCustomizationForm = gvLines.Columns["Price"].OptionsColumn.ShowInCustomizationForm = gvLines.Columns["LineTotal"].OptionsColumn.ShowInCustomizationForm = false;
            //}

            gvPOrder.MakeColumnInvisible("Ü", "T", "StatusId", "LangId", "Email", "CreatorId", "TotalTransfered", "CustomerId");
            if (SiparisTipi == 2)
                gvPOrder.MakeColumnInvisible("QtyIade", "QtyIskonto", "ToplamMT");

            gvPOrder.BestFitColumns();
        }

        DataSet ds;
        BindingSource bs;

        private void Orders_Load(object sender, EventArgs e)
        {
            gcPOrder.Enabled = false;
            gcPOrderDetail.Enabled = false;
            if (Data.IsLookupInitialized)
                Data_LookupsLoaded();
            else
                Data.LookupInitialized += Data_LookupsLoaded;
        }

        private void Data_LookupsLoaded()
        {
            BindData();

            gvLines.RowCellClick += gvPOrderDetail_RowCellClick;
            gvLines.CustomDrawCell += gvPOrderDetail_CustomDrawCell;
            gvLines.CalcRowHeight += gvLines_CalcRowHeight;
            gvLines.RowCellStyle += gvPOrder_RowCellStyle;
            gvLines.CellValueChanged += gvLines_CellValueChanged;


            bool first = true;
            GridManager gm = GridManager.GetManager(gvLines);
            foreach (AkerDB.StatusRow sr in Data.DB.Status.Rows)
            {
                if (sr.StatusId > 2)
                {
                    DevExpress.Utils.Menu.DXMenuItem menu = gm.GridMenu.AddMenu(sr.Status, SetLineStatus, first);
                    menu.Tag = gvLines;
                    first = false;
                }
            }

            if (SiparisTipi == 1)
                this.Text = "Üretim Siparişleri";
            else if (SiparisTipi == 2)
                this.Text = "İplik Siparişleri";

            gvPOrder.ViewCaption = "Siparişler";
            gvLines.ViewCaption = "Sipariş Detayları";

            gvPOrder.CustomDrawCell += gvPOrder_CustomDrawCell;

            GridManager gmOrder = GridManager.GetManager(gvPOrder);
            gmOrder.GridMenu.AddMenu("Siparişi Düzenle", EditOrder);
            gmOrder.GridMenu.AddMenu("Siparişi Yazdır", PrintOrder);

            if (AppSession.UserInfo.Yonetici)
                gmOrder.GridMenu.AddMenu("Siparişi Sil !", DelOrder);

            first = true;
            gm = GridManager.GetManager(gvPOrder);
            foreach (AkerDB.StatusRow sr in Data.DB.Status.Rows)
            {
                if (sr.StatusId < 3)
                {
                    gm.GridMenu.AddMenu(sr.Status, SetStatus, first);
                    first = false;
                }
            }
            gvPOrder.RowCellStyle += gvPOrder_RowCellStyle;

            gvPOrder.RowStyle += gvPOrder_RowStyle;
            gvLines.RowStyle += gvPOrder_RowStyle;

            gvPOrder.FocusedRowChanged += gvPOrder_FocusedRowChanged;
            gvPOrder.CalcRowHeight += gvPOrder_CalcRowHeight;

            bbiDetay.PerformClick();
            gcPOrder.Enabled = true;
            gcPOrderDetail.Enabled = true;

            bbiOK.PerformClick();
            bbiShowCancelled.PerformClick();
        }

        void gvPOrder_RowStyle(object sender, RowStyleEventArgs e)
        {
            GridView gv = sender as GridView;
            if (e.RowHandle < 0)
                return;

            //if (e.RowHandle == gv.FocusedRowHandle)
            //    e.Appearance.BackColor = Color.LightYellow;

            if (gv.GetDataRow(e.RowHandle)["Status"].ToStringNN() == "İptal")
            {
                e.Appearance.BackColor = Color.LightCyan;
                e.Appearance.FontStyleDelta = FontStyle.Strikeout;
            }
        }

        private void PrintOrder(object sender, EventArgs e)
        {
            DataRow dr = gvPOrder.GetFocusedDataRow();
            int podId = dr["POrderId"].ToIntNN();
            int langId = dr["LangId"].ToIntNN(); ;
            string email = dr["Email"].ToStringNN();

            if (SiparisTipi == 1)
            {
                SiparisFormu report = new SiparisFormu(podId, langId);
                AppSession.MainForm.ShowMdiChildForm(typeof(ReportViewer), report, email, "Sipariş No:" + podId);
            }
            else if (SiparisTipi == 2)
            {
                Iplik.SiparisFormu report = new Iplik.SiparisFormu(podId, langId);
                AppSession.MainForm.ShowMdiChildForm(typeof(ReportViewer), report, email, "Sipariş No:" + podId);
            }
        }

        void gvPOrder_CustomDrawCell(object sender, RowCellCustomDrawEventArgs e)
        {
            if (e.Column.FieldName == "Status" && e.RowHandle > -1)
            {
                int u = gvPOrder.GetRowCellValue(e.RowHandle, "Ü").ToIntNN();
                int t = gvPOrder.GetRowCellValue(e.RowHandle, "T").ToIntNN();

                if (u == -1)
                    u = 0;
                if (t == -1)
                    t = 0;

                Brush ellipseBrush = Brushes.LightSkyBlue;
                Rectangle r = e.Bounds;


                if ((u > 0 || t > 0) && u + t > 0)
                {
                    decimal pay = r.Width / Convert.ToDecimal(u + t);

                    if (t > 0)
                    {

                        int a = 0;
                        a++;
                    }

                    RectangleF ru = new RectangleF((float)r.X, (float)r.Y, (float)pay * u, (float)r.Height);
                    ellipseBrush = Brushes.Yellow;
                    e.Graphics.FillRectangle(ellipseBrush, ru);
                    e.Appearance.DrawString(e.Cache, "Ü", new Rectangle(r.X + 3, r.Y, r.Width - 12, r.Height));

                    ru = new RectangleF((float)r.X + (float)ru.Width, (float)r.Y, (float)pay * t, (float)r.Height);
                    ellipseBrush = Brushes.Aqua;
                    e.Graphics.FillRectangle(ellipseBrush, ru);
                    e.Appearance.DrawString(e.Cache, "T", new Rectangle(ru.X.ToIntNN() + 3, ru.Y.ToIntNN(), ru.Width.ToIntNN() - 12, ru.Height.ToIntNN()));
                }
                else
                {
                    if (e.DisplayText == "Onaylandı")
                    {
                        ellipseBrush = Brushes.LightGreen;
                    }
                    else
                    {
                        ellipseBrush = Brushes.White;
                    }

                    e.Graphics.FillRectangle(ellipseBrush, r);

                    r.Width -= 12;
                    e.Appearance.DrawString(e.Cache, e.DisplayText, r);
                }

                e.Handled = true;
            }
        }

        private void DelOrder(object sender, EventArgs e)
        {
            if (XtraMessageBox.Show("Bağlı tüm irsaliyeler de silinecek. Emin misiniz?", "Delete Row", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                int podId = gvPOrder.GetFocusedRowCellValue("POrderId").ToIntNN();
                Data.DM.ExecuteNonQuery("DelPOrder", podId);
                //RefreshData();
            }
        }

        void gvPOrder_CalcRowHeight(object sender, RowHeightEventArgs e)
        {
            //if (!gvLines.IsFilterRow(e.RowHandle))
            //    e.RowHeight = 50;
        }

        void gvLines_CellValueChanged(object sender, CellValueChangedEventArgs e)
        {
            gvLines.CellValueChanged -= gvLines_CellValueChanged;

            if (e.Column.FieldName.ToLower().Contains("new"))
            {
                decimal qtySipMt = (decimal)gvLines.GetRowCellValue(e.RowHandle, "Meters").ToDecimalNN();
                decimal qtySipKG = (decimal)gvLines.GetRowCellValue(e.RowHandle, "KG").ToDecimalNN();

                decimal qtyNewMt = (decimal)gvLines.GetRowCellValue(e.RowHandle, "NewTransferMT").ToDecimalNN();
                decimal qtyNewKG = (decimal)gvLines.GetRowCellValue(e.RowHandle, "NewTransferKG").ToDecimalNN();

                decimal qtyOld = (decimal)gvLines.GetRowCellValue(e.RowHandle, "TotalTransfered").ToDecimalNN();

                if (qtySipMt > 0 && qtyNewKG > 0)
                {
                    gvLines.SetRowCellValue(e.RowHandle, "NewTransferKG", null);
                    DevExpress.XtraEditors.XtraMessageBox.Show("Talep cinsi ile sevkiyat aynı cins olmalı !", "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else if (qtySipKG > 0 && qtyNewMt > 0)
                {
                    gvLines.SetRowCellValue(e.RowHandle, "NewTransferMT", null);
                    DevExpress.XtraEditors.XtraMessageBox.Show("Talep cinsi ile sevkiyat aynı cins olmalı !", "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    //decimal qtyNew = (decimal)e.Value;
                    //if (qtyNew + qtyOld > (qtySipMt + qtySipKG) * Convert.ToDecimal(1.05))
                    //{
                    //    DevExpress.XtraEditors.XtraMessageBox.Show("Talep edilen miktarın ± %5'i kabul edilebilir !", "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    //    gvLines.SetRowCellValue(e.RowHandle, "NewTransferKG", null);
                    //    gvLines.SetRowCellValue(e.RowHandle, "NewTransferMT", null);
                    //}
                }
            }

            gvLines.CellValueChanged += gvLines_CellValueChanged;
        }




        void gvPOrder_FocusedRowChanged(object sender, FocusedRowChangedEventArgs e)
        {
            gvLines.BestFitColumns();
            gvLines.ViewCaption = "Sip.No: " + gvPOrder.GetFocusedRowCellValue("POrderId").ToStringNN() + " / " + gvPOrder.GetFocusedRowCellValue("Brand").ToStringNN();
            gvLines.Columns["Status"].Width = 100;
        }


        private void gvLines_CalcRowHeight(object sender, RowHeightEventArgs e)
        {
            if (!gvLines.IsFilterRow(e.RowHandle))
                e.RowHeight = 50;
        }

        void gvPOrderDetail_CustomDrawCell(object sender, RowCellCustomDrawEventArgs e)
        {
            if (e.Column.FieldName == "Thumb" && e.RowHandle > -1)
            {
                int bazProductId = gvLines.GetRowCellValue(e.RowHandle, "BazProductId").ToIntNN();

                if (bazProductId > -1)
                {
                    AkerDB.ProductRow pr = Data.DB.Product.FindByProductId(bazProductId);

                    if (!pr.IsThumbnailNull())
                    {
                        MemoryStream ms = new MemoryStream(pr.Thumbnail);
                        e.Graphics.DrawImage(Image.FromStream(ms), e.Bounds.X, e.Bounds.Y);
                        e.Handled = true;
                    }
                }
            }
        }

        void gvPOrderDetail_RowCellClick(object sender, RowCellClickEventArgs e)
        {
            if (e.Column.FieldName == "Thumb")
            {
                int bazProductId = (int)gvLines.GetFocusedRowCellValue("BazProductId");

                AkerDB.ProductRow pr = Data.DB.Product.FindByProductId(bazProductId);

                if (!pr.IsThumbnailNull())
                {
                    ImageViewer iv = new ImageViewer(bazProductId);
                    iv.ShowDialog();
                }
            }
        }


        void gvPOrder_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            if (e.RowHandle < 0)
                return;

            if (e.RowHandle == gvPOrder.FocusedRowHandle)
                e.Appearance.BackColor = Color.LightYellow;

            if (e.Column.FieldName == "Status")
            {
                if (e.CellValue.ToStringNN() == "Onay Bekleniyor")
                    e.Appearance.BackColor = Color.White;
                else if (e.CellValue.ToStringNN() == "Onaylandı")
                    e.Appearance.BackColor = Color.LightGreen;
            }

            else if (e.Column.FieldName == "Tutar")
                e.Appearance.FontStyleDelta = FontStyle.Bold;

            else if (e.Column.FieldName == "KalanGun")
            {
                int kalanGun = e.CellValue.ToIntNN();

                if (kalanGun == 0)
                    e.Appearance.ForeColor = Color.White;
                else if (e.CellValue.ToIntNN() < 0)
                {
                    e.Appearance.BackColor = Color.Red;
                    e.Appearance.ForeColor = Color.White;
                    e.Appearance.FontStyleDelta = FontStyle.Bold;
                }
            }
        }

        private void EditOrder(object sender, EventArgs e)
        {
            if (gvLines.FocusedRowHandle > -1)
            {
                DataRow dr = gvPOrder.GetFocusedDataRow();

                int podId = dr["POrderId"].ToIntNN();
                int userId = dr["CreatorId"].ToIntNN();
                string status = dr["Status"].ToStringNN();
                int statusId = Data.DB.Status.Select("Status='" + status + "'")[0]["StatusId"].ToIntNN();

                if (AppSession.UserInfo.Yonetici || AppSession.UserInfo.YetkiId == 4)
                    AppSession.MainForm.ShowMdiChildForm(typeof(YeniSiparis), podId);
                else if (userId == AppSession.UserInfo.UserId)
                    if (statusId == 1)
                        AppSession.MainForm.ShowMdiChildForm(typeof(YeniSiparis), podId);
                    else
                        DevExpress.XtraEditors.XtraMessageBox.Show("Onaylanan siparişleri sadece yönetim değiştirebilir !", "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error);
                else
                    DevExpress.XtraEditors.XtraMessageBox.Show("Sadece kendi oluşturduğunuz siparişleri değiştirebilirsiniz.", "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
                DevExpress.XtraEditors.XtraMessageBox.Show("Sipariş satırı üzerinde tıklayınız.", "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        private void SetStatus(object sender, EventArgs e)
        {
            string curStatus = gvPOrder.GetFocusedRowCellValue("Status").ToStringNN();
            int curStatusId = Data.DB.Status.Select("Status='" + curStatus + "'")[0]["StatusId"].ToIntNN();

            string status = ((DevExpress.Utils.Menu.DXMenuItem)(sender)).Caption;
            int statusId = Data.DB.Status.Select("Status='" + status + "'")[0]["StatusId"].ToIntNN();

            if (AppSession.UserInfo.Yonetici || SiparisTipi == 2)
                SetStatus(status, statusId);
            if (statusId == curStatusId + 1 || statusId == 5 /*İptal*/)
                SetStatus(status, statusId);
            else if (statusId == 1)
                XtraMessageBox.Show("Sadece yöneticiler durumu resetleyebilir.", "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error);
            else
                XtraMessageBox.Show("Sadece bir sonraki adıma geçebilirsiniz !", "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        private void SetLineStatus(object sender, EventArgs e)
        {
            int[] rowHandles = gvLines.GetSelectedRows();

            DevExpress.Utils.Menu.DXMenuItem menu = (DevExpress.Utils.Menu.DXMenuItem)sender;
            string status = menu.Caption;

            foreach (int rowHandle in rowHandles)
            {
                DataRow dr = gvLines.GetDataRow(rowHandle);

                if (status != "İptal" && dr["Status"].ToString() == "Onay Bekleniyor")
                {
                    XtraMessageBox.Show("Önce sipariş satırını onaylayın!", "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                GridView view = (GridView)menu.Tag;
                int statusId = Data.DB.Status.Select("Status='" + status + "'")[0]["StatusId"].ToIntNN();

                int curStatusId = -1;
                string curStatus = dr["Status"].ToStringNN();
                if (curStatus != "")
                    curStatusId = Data.DB.Status.Select("Status='" + curStatus + "'")[0]["StatusId"].ToIntNN();

                if (AppSession.UserInfo.Yonetici || SiparisTipi == 2)
                    SetStatusLine(status, statusId, rowHandle);
                else if ((curStatusId == -1 && statusId == 3) || statusId == curStatusId + 1 || statusId == 5 /*İptal*/)
                    SetStatusLine(status, statusId, rowHandle);
                else if (statusId == 1)
                    XtraMessageBox.Show("Sadece yöneticiler durumu resetleyebilir.", "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error);
                else
                    SetStatusLine(status, statusId, rowHandle);  //XtraMessageBox.Show("Sadece bir sonraki adıma geçebilirsiniz !", "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            //if (rowHandles.Length > 0)
            //    RefreshData();
        }

        private void SetStatus(string status, int statusId)
        {
            int podId = gvPOrder.GetFocusedRowCellValue("POrderId").ToIntNN();
            DataTable dt = Data.DM.ExecuteDataTable("UpdateStatus", podId, statusId, AppSession.UserInfo.UserId);
            gvPOrder.SetFocusedRowCellValue("Status", status);
        }

        private void SetStatusLine(string status, int statusId, int RowHandle)
        {
            int porderLinesId = gvLines.GetDataRow(RowHandle)["POrderLinesId"].ToIntNN();
            DataTable dt = Data.DM.ExecuteDataTable("UpdateStatusLine", porderLinesId, statusId, AppSession.UserInfo.UserId);
            gvLines.SetRowCellValue(RowHandle, "Status", status);

            //RefreshData();

            //if (statusId == 3)
            //{
            //    gvPOrder.SetRowCellValue(gvPOrder.FocusedRowHandle, "T", gvPOrder.GetFocusedRowCellValue("T").ToIntNN() - 1);
            //    gvPOrder.SetRowCellValue(gvPOrder.FocusedRowHandle, "Ü", gvPOrder.GetFocusedRowCellValue("Ü").ToIntNN() + 1);
            //}
            //else
            //{
            //    gvPOrder.SetRowCellValue(gvPOrder.FocusedRowHandle, "Ü", gvPOrder.GetFocusedRowCellValue("Ü").ToIntNN() - 1);
            //    gvPOrder.SetRowCellValue(gvPOrder.FocusedRowHandle, "T", gvPOrder.GetFocusedRowCellValue("T").ToIntNN() + 1);
            //}
        }


        private void bbiDetay_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (splitter.PanelVisibility == SplitPanelVisibility.Both)
            {
                bbiDetay.Caption = "Detayları Göster";
                splitter.PanelVisibility = SplitPanelVisibility.Panel1;
            }
            else
            {
                splitter.PanelVisibility = SplitPanelVisibility.Both;
                bbiDetay.Caption = "Detayları Gizle";
            }
        }

        private void btnYenile_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            RefreshData();
        }

        private void bbiShowCancelled_CheckedChanged(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ApplyFilter();
        }

        private void ApplyFilter()
        {
            if (bbiShowCancelled.Checked && bbiOK.Checked)
                gvPOrder.Columns["Status"].ClearFilter();
            else
            {
                List<string> filters = new List<string>();

                if (!bbiShowCancelled.Checked)
                    filters.Add("Status <> 'İptal'");

                if (!bbiOK.Checked)
                    filters.Add("not (ToplamArtikel=T)");
                //filters.Add("not (Ü=0 and T>0)");


                string filter = string.Join(" and ", filters.ToArray());

                gvPOrder.Columns["Status"].FilterInfo = new ColumnFilterInfo(filter);
            }
        }

        public void RefreshData()
        {
            GridColumnSortInfoCollection sortInfo = gvPOrder.SortInfo;

            GridColumnSortInfo[] savedInfo = new GridColumnSortInfo[sortInfo.Count];
            ArrayList sortList = new ArrayList(sortInfo);
            sortList.CopyTo(savedInfo, 0);

            int POrderId = gvPOrder.GetFocusedRowCellValue("POrderId").ToIntNN();
            ds = Data.DM.ExecuteDataSet("GetPOrders", true, 1);
            BindData();
            ApplyFilter();

            foreach (GridColumnSortInfo si in sortList)
                gvPOrder.SortInfo.Add(gvPOrder.Columns[si.Column.FieldName], si.SortOrder);

            //gvPOrder.SortInfo.Add(gvPOrder.Columns["OrderDate"], DevExpress.Data.ColumnSortOrder.Descending);
            //gvPOrder.SortInfo.ClearAndAddRange(savedInfo); //restore
            int rh = gvPOrder.LocateByValue("POrderId", POrderId);
            gvPOrder.FocusedRowHandle = rh;
            gvPOrder.MakeRowVisible(rh);
        }
    }
}
